import React, { PureComponent } from "react";
import { View, StyleSheet, SafeAreaView, Text, DeviceEventEmitter, FlatList, TouchableOpacity, ScrollView, ToastAndroid } from "react-native";
import { Button, Icon, Overlay } from "react-native-tengits-elements";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import { TText } from "../common/Widgets/WidgetDefault";
import DataCenter from "../logic/DataCenter";
import { holeType2Name } from "../logic/LogicConstant";
import { TNormalExceptCircle, TNumberCircle, TUpDownText } from "./Components/NormalExceptCircle";
import { scaleSize } from "../common/Utils/ToolUtils";
import { Colors, FontSize } from "../common/Theme/TTheme";
import { OverlaySegmentAdjust } from "./Components/SegmentAdjust";
import UICommandExecute from "../logic/UICommandExecute";
import { OverlayStrategyList } from "./Components/StrategyList";
import { TEmptyView, TSingleHoleEmptyView } from "./Components/SubItemComponent";
import Tooltip from 'react-native-walkthrough-tooltip';
import moment from "moment";
import { queryStrategyBrightness } from "../logic/Utils";
import _ from 'lodash';
import { Loop_Device_Base } from "../libs/SerialCommon";

export default class SingleHolePage extends React.PureComponent {
    constructor(props) {
        super(props);
        let data = DataCenter.getTunnelGates();
        this.state = {
            data: data,
            strategyList: DataCenter.getStrategyList(),
            batchBrightnessVisible: false,
            strategyListVisible: false,
            selectItem:{},
            toolTipVisible: Array.from({ length: (data||[]).length },item => false),
        };
    }

    componentDidMount() {
        this.tunnelListener = DeviceEventEmitter.addListener("tunnelCabinet", () =>{
            let data = DataCenter.getTunnelGates();
            this.setState({
                data: data,
                toolTipVisible: Array.from({ length: (data||[]).length },item => false),
            });
        });
        this.strategyListListener = DeviceEventEmitter.addListener("strategyList", () =>{
            this.setState({
                strategyList: DataCenter.getStrategyList(),
            });
        });
    }

    componentWillUnmount() {
        this.tunnelListener.remove();
        this.strategyListListener.remove();
    }

    getHeadTitle = ()=>{
        let baseName = DataCenter.getTunnleBaseInfo();
        return baseName;
    }

    renderHeader() {
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                    <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                </View>
        </View>
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    navigation.replace('Main')
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice')
                }}/>
            </View>
    }

    batchSliderCallback = (data, value) => {
        //console.log("slider:",data, value);
        const{selectItem} = this.state;
        UICommandExecute.onSingleHoleRealSlider(data.sectionId, value);
    }

    batchSliderCompleteCallback = (data, value) => {
        UICommandExecute.onSingleHoleSliderComplete(data.sectionId, value, false);
    }

    toggleOverlay = (key) => {
        const{selectItem} = this.state;
        if(key == "SegmentLight") {
            this.setState({batchBrightnessVisible: false});
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
        }
    }

    onSure = (key, params) => {
        const{selectItem} = this.state;
        if(key == "SegmentLight") {
            params && UICommandExecute.onSingleHoleSliderComplete(params.data.sectionId, params.light, true);
            this.setState({batchBrightnessVisible: false});
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
            params && UICommandExecute.onSingleHoleStrategySelect(selectItem.sectionId, params.id);
        }
    }

    querySegmentLoopsValue(sectionId, brightness) {
        let tip = [];
        let loops = DataCenter.queryLoopsInSection(sectionId);
        let ret = DataCenter.queryGateLoopsBrightness(DataCenter.gateId, loops.local) || [];
        if(ret && ret.length > 0) {
            tip.push({name:"本柜", loops: ret});
        }
        for(let gate of Object.keys(loops.colony)) {
            let gate_loop = DataCenter.queryGateLoopsBrightness(gate, loops.colony[gate]);
            if(gate_loop && gate_loop.length > 0) {
                tip.push({name:gate_loop[0].gateName, loops: gate_loop});
            }
            
        }
        return tip;
    }

    renderListItem = ({item, index, separators}) => {
        const{toolTipVisible, strategyList} = this.state;
        let targetStrategy = DataCenter.queryStrategyById(item.strategyId);
        let brightness = item.brightness || queryStrategyBrightness(targetStrategy?.setting);
        let result = this.querySegmentLoopsValue(item.sectionId, item.brightness);
        let fault = false;
        let tipView = result.map((tip,ri)=>{
            const group_data = _.groupBy(tip.loops||[], (item)=>Math.ceil(item.loopNumber/Loop_Device_Base));
            const keys = Object.keys(group_data||{});
            return keys.map((loopControllNumber)=>{
                    let brightnessView = group_data[loopControllNumber].map((loop,ix)=>{
                        let subView = <Text style={{color: Colors.text1_color, fontSize: FontSize.h5_font}}>
                                        {loop.loopCurrentValue}
                                        </Text>;
                        if(loop.loopCurrentValue != brightness) {
                            subView = <Text style={{ color: Colors.tip_color, fontSize: FontSize.h5_font}}>
                                        {loop.loopCurrentValue}
                                        </Text>;
                            fault = true;
                        }
                        return <Text key={"sub_"+ix} style={{marginTop:scaleSize(12), color: Colors.text1_color, fontSize: FontSize.h5_font}}>{loop.loopName+"的亮度为："}{subView}</Text>
                    })
                    return <Text key={"text_"+index + "_" + ri} style={[{color: Colors.text2_color, fontSize: FontSize.h4_font}, ri>0 ? {marginTop:scaleSize(24)} : {}]}>
                            {tip.name+"\n"}<View style={{flexDirection:'column'}}>
                                <Text style={{color: Colors.text1_color, fontSize: FontSize.h5_font}}>{"回路控制器"+loopControllNumber}</Text>
                                {brightnessView}
                                </View>
                        </Text>
                });
        })
        let headTitleView = (
            <TouchableOpacity style={[styles.headCellContainer, fault? {backgroundColor:'#FC717B'} : {}]} onPress={()=>{
                toolTipVisible[index] = true;
                this.setState({
                    toolTipVisible: [...toolTipVisible]
                })
            }}>
                <Text style={{textAlign:'center', width:scaleSize(120), fontSize: FontSize.h4_font, color: Colors.white}}>{`${item.sectionName}`}</Text>
            
            </TouchableOpacity>
        );
        return <View key={index} style={[styles.columnContainer, {height:scaleSize(434)}]}>
            {result && result.length > 0 ? <Tooltip
            arrowSize={{width:0,height:0}}
            contentStyle={{padding: scaleSize(24)}}
            isVisible={toolTipVisible[index]}
            content={
                <ScrollView showsVerticalScrollIndicator={true}>
                    <TouchableOpacity activeOpacity={1} onPress={()=>{}}>
                        {tipView}
                    </TouchableOpacity>
                </ScrollView>
                }
            placement={index >5 ? "left": "right"}
            onClose={() => {
                toolTipVisible[index] = false;
                this.setState({
                    toolTipVisible: [...toolTipVisible]
                })
            }}
            >
                {headTitleView}
        </Tooltip> : headTitleView}
        <TouchableOpacity style={styles.contentCellContainer} onPress={()=>{
            this.setState({
                selectItem: {sectionName: item.sectionName, sectionId: item.sectionId, brightness: brightness},
                batchBrightnessVisible:true
            })
        }}>
            <Text style={{fontSize: FontSize.h4_font, color: Colors.text4_color}}>{`${brightness||"无"}`}</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.contentCellContainer} onPress={()=>{
            if(!strategyList || strategyList.length <= 0) {
                ToastAndroid.show("当前无策略配置", ToastAndroid.SHORT);
            } else {
                this.setState({
                    selectItem: {sectionName: item.sectionName, sectionId: item.sectionId, id: item.strategyId},
                    strategyListVisible:true
                });
            }
        }}>
            <Text style={{fontSize: FontSize.h4_font, color: Colors.text4_color}}>{`${targetStrategy?.name||"无"}`}</Text>
        </TouchableOpacity>
        </View>
    }

    renderListHead = () => {
        return <View style={[styles.columnContainer,{width:scaleSize(100), height:scaleSize(434)}]}>
                <TouchableOpacity style={[styles.headCellContainer]} onPress={()=>{}}>
                    <Text style={{fontSize: FontSize.h4_font, color: Colors.white}}>{`${holeType2Name(DataCenter.tunnelType)}`}</Text>
                </TouchableOpacity>
                <View style={styles.contentCellContainer}>
                    <Text style={{fontSize: FontSize.h4_font,}}>{"亮度"}</Text>
                </View>
                <View style={styles.contentCellContainer}>
                    <Text style={{fontSize: FontSize.h4_font}}>{"策略"}</Text>
                </View>
                </View>
    }

    renderContent() {
        const{data} = this.state;
        if(data && data.length > 0) {
            return <View style={{flex:1, paddingBottom:scaleSize(40), flexDirection:'row', alignItems:'center'}}>
                    <Button buttonStyle={{width:scaleSize(85), height:scaleSize(88), backgroundColor:'transparent'}}
                    icon={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' color={Colors.button_color}/>}
                    onPress={()=>{
                        this.listRef && this.listRef.scrollToIndex({index:0});
                    }}/>
                    <View style={{flexDirection:'row', width:scaleSize(1188), backgroundColor: '#ECEDFB'}}>
                    {this.renderListHead()}
                    <FlatList
                        style={{flex:1}}
                        ref={(ref)=>{this.listRef = ref}}
                        horizontal
                        data={data||[]}
                        showsHorizontalScrollIndicator={false}
                        stickyHeaderIndices={[1]}
                        renderItem={this.renderListItem}
                        keyExtractor={(item, index) => `${index}`}
                    />
                    </View>
                    <Button buttonStyle={{width:scaleSize(85), height:scaleSize(88), backgroundColor:'transparent'}}
                    icon={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' color={Colors.button_color}/>}
                    onPress={()=>{
                        this.listRef && this.listRef.scrollToEnd();
                    }}/>
        </View>
        } else {
            return <View style={{flex:1, flexDirection:'row', alignItems:'center', paddingHorizontal: scaleSize(85)}}>
                <TSingleHoleEmptyView/>
            </View>
        }
    }

    render() {
        const{batchBrightnessVisible, strategyListVisible, strategyList, selectItem, data} = this.state;
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                <View style={{flexDirection:'row', paddingHorizontal: scaleSize(85), paddingVertical:scaleSize(30)}}>
                    <View style={[styles.cardContainer]}>
                        <View style={{flexDirection:'row', paddingVertical: scaleSize(20), justifyContent:'space-around', alignItems:'center'}}>
                            <TNumberCircle title={"洞内光强"} number={"--"} bgColor={Colors.perple_color}/>
                            <TNumberCircle title={"洞外光强"} number={"--"} bgColor={Colors.blue_color}/>
                        </View>
                    </View>
                    <View style={[styles.cardContainer, {marginLeft: scaleSize(30)}]}>
                        <View style={{flexDirection:'row', paddingVertical: scaleSize(20), justifyContent:'space-around', alignItems:'center'}}>
                            <TUpDownText title={"左洞车检器1"} number={"--"}/> 
                            <TUpDownText title={"左洞车检器2"} number={"--"}/> 
                        </View> 
                    </View>
                </View>
                {this.renderContent()}
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
                <Overlay overlayStyle={{padding:0}} isVisible={batchBrightnessVisible} onBackdropPress={()=>{this.toggleOverlay("SegmentLight")}} fullScreen>
                    <OverlaySegmentAdjust data={selectItem}
                    sliderCallback={this.batchSliderCallback}
                    sliderCompleteCallback={this.batchSliderCompleteCallback}
                    toggleOverlay={this.toggleOverlay} 
                    onSure={this.onSure}/>
                </Overlay>
                <Overlay overlayStyle={{padding:0}} isVisible={strategyListVisible} onBackdropPress={()=>{this.toggleOverlay("StrategySelect")}} fullScreen>
                    <OverlayStrategyList
                    data={strategyList}
                    id={selectItem?.id}
                    canSel={true}  
                    toggleOverlay={this.toggleOverlay}
                    onSure={this.onSure}/>
                </Overlay>
            </SafeAreaView>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        backgroundColor: Colors.page_bg_color, 
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
    cardContainer:{
        flex:1,
        flexDirection:'column',
        backgroundColor: Colors.white,
        borderRadius: scaleSize(6),
    },
    columnContainer:{
        flexDirection:'column', 
        width:scaleSize(120),
        //height:scaleSize(460),
        borderRightWidth:1,
        borderRightColor: "#DCDDF2"
    },
    headCellContainer:{
        justifyContent:'center', 
        alignItems:'center',
        height:scaleSize(84),  
        backgroundColor: Colors.button_color
    },
    retCellContainer:{
        flex:1,
        backgroundColor:'#ECEDFB', 
        borderBottomWidth:1, 
        borderBottomColor: "#DCDDF2"
    },
    contentCellContainer:{
        flex:1,
        justifyContent:'center', 
        alignItems:'center', 
        borderBottomWidth:1, 
        borderBottomColor: "#DCDDF2", 
        //height:scaleSize(144), 
        backgroundColor: Colors.white
    }
});